<?php

namespace App\Api\Auth\Controllers;

use App;
use App\Api\Auth\Models\UsersOpenId;
use App\Api\Auth\Requests\AuthLoginRequest;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Api\Auth\Services\PermissionServices;
use App\Api\Auth\Requests\UserAddRequest;
use App\Api\Auth\Requests\ResetPasswordRequest;
use App\Api\Auth\Services\OrderService;
use App\Api\Auth\Requests\PermissionRequest;
use App\Api\Auth\Models\PermissionUser;
use App\Api\Auth\Models\Permissions;
use App\Api\Auth\Requests\FunctionRequest;
use Auth;
use DB;


class PermissionController extends Controller
{
    /**
     * 登录
     * @param AuthLoginRequest $request
     * @return array
     */
    public function login(AuthLoginRequest $request)
    {
        $params = $request->request->all();

        $remember = data_get($params, 'remember', 0);
        if ($remember) {
            $remember = true;
        } else {
            $remember = false;
        }
        if(!empty($params['name'])){
            $res = User::where('name','=',$params['name'])->value('status');
            if(empty($res)){
                $res = User::where('mobile','=',$params['name'])->value('status');
            }
            if($res == config('auth.status.stop_use')){
                throw new \LogicException('账号已停用', 300);
            }
            if ($res == config('auth.status.deleted')) {
                throw new \LogicException('账号不存在', 400);
            }
        }else{
            throw new \LogicException('用户名或密码错误', 20);
        }
        if (Auth::attempt(['name' => $params['name'], 'password' => $params['password']], $remember) or Auth::attempt(['mobile' => $params['name'], 'password' => $params['password']], $remember)) {
            $user = App\Api\Auth\Services\AuthService::getUserRole(Auth::user());
            $permission_id = PermissionUser::where('user_id',data_get($user,'id',0))->value('permission_id');
            $user['functions'] = App\Api\Auth\Models\PermissionFunction::where('permission_id',$permission_id)->get();
            if(!empty($user['functions'])) {
                foreach ($user['functions'] as $key => $function){
                    $function_id = $function['func_id'];
                    $func = App\Api\Auth\Models\Functions::where('id',$function_id)->first();
                    $user['functions'][$key] = $func;
                }
            }

            return $this->formatOutput($user);
        } else {
            throw new \LogicException('用户名或密码错误', 20);
        }
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $users  = \DB::table('users')->limit(5)->get();
        dd($users);
        return $this->formatOutput(1);
    }

    public function store(Request $request)
    {
        $params = $request->all();
    }

    public function rosList(Request $request)
    {
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $datas = PermissionServices::rosList();
        return $this->formatOutput($datas);
    }

    public function userList(Request $request)
    {
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $params              = $request->all();
        $params['page']      = data_get($params, 'page', 1);
        $params['page_size'] = data_get($params, 'page_size', 20);
        $datas               = PermissionServices::userList($params);
        return $this->formatOutput($datas);
    }

    public function userAdd(UserAddRequest $request)
    {
        $params = $request->all();
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $data   = PermissionServices::userAdd($params);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }

    public function userDel(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }

        $delUserId = data_get($params, 'user_id', '');
        $bUser = App\Api\Auth\Models\Users::where('user_id', '=', $delUserId)
            ->where('shop_id', '=', $user->id)
            ->first();

        if (empty($bUser)) {
            throw new \LogicException('不存在的账户', 120);
        }
        $bUser->delete();
        PermissionUser::where('user_id', '=', $delUserId)
            ->delete();

        User::find($delUserId)
            ->delete();

        return $this->formatOutput('success');
    }

    public function userStatus(Request $request){
        $params = $request->all();
        $id = data_get($params,'id',0);
        $status = data_get($params,'status',0);
        if ($status == 10) {
            $status = -100;
        }
        if ($status == 0) {
            $status = 100;
        }
        if ($status == -1) {
            $status = -200;
        }
        $data = App\Api\Auth\Models\Users::where('id',$id)->update(['status'=>$status]);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }

    public function userChange(Request $request){
        $user          = authUser();
        $shopId        = App\Api\Auth\Services\UserService::getShopId($user);
        $params        = $request->all();
        $ids           = data_get($params, 'ids', []);
        $permission_id = data_get($params, 'permission_id', 0);
        if (empty($ids) || !is_array($ids) || !$permission_id) throw new \LogicException('值不能为空');
        foreach ($ids as $id) {
            if (App\Api\Auth\Models\Users::where('user_id', $id)->where('shop_id', $shopId)->first()) {
                PermissionUser::where('user_id', $id)->first() ?
                    PermissionUser::where('user_id', $id)->update(['permission_id' => $permission_id])
                    : PermissionUser::create(['user_id' => $id, 'permission_id' => $permission_id]);
            }
            //PermissionUser::updateOrCreate(['user_id'=>$id],['permission_id' => $permission_id]);//没有id没法用
        }
        return $this->formatOutput('成功');
    }

    public function userUpdate(UserAddRequest $request)
    {
        $params = $request->all();
        $data   = PermissionServices::userUpdate($params);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }

    public function resetPassword(ResetPasswordRequest $request)
    {
        $params  = $request->all();
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $id = data_get($params, 'id', '');
        $isExist = App\Api\Auth\Models\Users::where('shop_id', '=', $user->id)
            ->where('id', '=', $id)
            ->first();
        if (empty($isExist)) {
            throw new \LogicException('缺少必要参数', 100);
        }
        $name = data_get($params, 'name', '');
        $password = data_get($params, 'password', '');
        $updates = [];
        if (!empty($name)) {
            $updates['login_name'] = $name.'@'.data_get(App\Api\Auth\Models\Users::where('id', '=', $user->id)->first(), 'login_name', '');
        }
        if (!empty($password)) {
            $updates['password'] = bcrypt($password);
        }
        info('update', $updates);
        if (!empty($updates)) {
            App\Api\Auth\Models\Users::find($id)
                ->update($updates);
        }
        return $this->formatOutput('success');
    }

    public function permissionList(Request $request)
    {
        $params              = $request->all();
        $params['page']      = data_get($params, 'page', 1);
        $params['page_size'] = data_get($params, 'page_size', 20);
        $datas               = PermissionServices::permissionList($params);
        return $this->formatOutput($datas);
    }

    public function permissionUpdate(PermissionRequest $request){
        $params = $request->all();
        $data   = PermissionServices::permissionUpdate($params);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }
    /*
     * api定义
     */
    public function operationApi(Request $request)
    {
//        $a =$request->getRequestUri();
//        print_r($a);exit;
//        echo 1;exit;
        $params = $request->all();
        $res = PermissionServices::operationApi($params);
        if($res == 'ok'){
            return $this->formatOutput('操作成功');
        }else{
            throw new \LogicException($res);
        }
    }

    /*
     * 删除api
     */
    public function deleteApi(Request $request){
        $id = $request->input('id');
        if(empty($id)){
            throw new \LogicException('id不能为空');
        }
        $res = PermissionServices::deleteApi($id);
        if($res == 'ok'){
            return $this->formatOutput('操作成功');
        }else{
            throw new \LogicException($res);
        }
    }
    /*
    * 操作角色所属功能
    */
    public function updatePermissionApi(Request $request){
        $params = $request->all();
        $res = PermissionServices::updatePermissionApi($params);
        if($res == 'ok'){
            return $this->formatOutput('操作成功');
        }else{
            throw new \LogicException($res);
        }
    }
    /*
     * 删除角色
     */
    public function deletePermission(Request $request){
        $id = $request->input('id');
        if(empty($id)){
            throw new \LogicException('id不能为空');
        }
        $res = PermissionServices::deletePermission($id);
        if($res == 'ok'){
            return $this->formatOutput('操作成功');
        }else{
            throw new \LogicException($res);
        }
    }

    public function permissionFunc(Request $request){
        $params = $request->all();
        $permission_id = data_get($params,'permission_id',0);
        $func_ids = data_get($params,'func_ids',[]);
        if (!$permission_id) throw new \LogicException('缺少参数');
        $res = PermissionServices::permissionFunction($permission_id,$func_ids);
        addAdminLogs([
            'table_name'=>'permission_func',
            'log_info'=>'修改岗位对应功能',
            'remark'=>serialize($params)
        ]);
        return $this->formatOutput($res);
    }

    public function permissionDelete(Request $request){
        $params = $request->all();
        $permission_id = data_get($params,'permission_id',0);
        try{
            DB::beginTransaction();
            Permissions::where('id',$permission_id)->delete();//部门or岗位
            Permissions::where('parent_id',$permission_id)->delete();//若删除的是部门则也删除相关岗位
            App\Api\Auth\Models\PermissionFunction::where('permission_id',$permission_id)->delete();
            PermissionUser::where('permission_id',$permission_id)->delete();
            DB::commit();
            addAdminLogs([
                'table_name'=>'permission_func',
                'log_info'=>'岗位删除',
                'remark'=>serialize($params)
            ]);
            addAdminLogs([
                'table_name'=>'permission_user',
                'log_info'=>'岗位删除',
                'remark'=>serialize($params)
            ]);
            return $this->formatOutput('成功');
        }catch (\Exception $e){
            DB::rollBack();
            throw new \LogicException($e->getMessage());
        }
    }

    public function funcsList(Request $request)
    {
        $params              = $request->all();
        $params['page']      = data_get($params, 'page', 1);
        $params['page_size'] = data_get($params, 'page_size', 20);
        $params['new'] = data_get($params, 'new', 0);
        $datas               = PermissionServices::funcsList($params);
        return $this->formatOutput($datas);
    }

    public function funcLists(Request $request){
        $id = $request->input('id',0);
        $new = $request->input('new',0);
        $datas               = PermissionServices::funcLists($id,$new);
        return $this->formatOutput($datas);
    }

    public function getuserList(Request $request){
        $id = $request->input('id',0);
        $datas = App\Api\Auth\Models\PermissionFunction::where('permission_id',$id)->get();
        return $this->formatOutput($datas);
    }

    public function funcsAdd(FunctionRequest $request)
    {
        $params = $request->all();
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $data   = PermissionServices::funcsAdd($params);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }

    public function funcsUpdate(FunctionRequest $request){
        $params = $request->all();
        $data   = PermissionServices::funcsUpdate($params);
        $res    = $data ? ['成功'] : ['失败'];
        addAdminLogs([
            'table_name'=>'functions',
            'tid'=>data_get($params,'id',0),
            'log_info'=>'功能修改',
            'remark'=>serialize($params)
        ]);
        return $this->formatOutput($res);
    }

    public function funcsDelete(Request $request){
        $params = $request->all();
        $id = data_get($params,'id',0);
        try{
            DB::beginTransaction();
            PermissionServices::funcDelete([$id]);
            DB::commit();
            addAdminLogs([
                'table_name'=>'functions',
                'tid'=>$id,
                'log_info'=>'功能删除',
                'remark'=>serialize($params)
            ]);
            return $this->formatOutput('成功');
        }catch (\Exception $e){
            DB::rollBack();
            throw new \LogicException($e->getMessage());
        }
    }

    public function funcApi(Request $request){
        $params = $request->all();
        $func_id = data_get($params,'func_id',0);
        $api_ids = data_get($params,'api_ids',[]);
        if (!$func_id) throw new \LogicException('缺少参数');
        $res = PermissionServices::funcApi($func_id,$api_ids);
        addAdminLogs([
            'table_name'=>'function_route',
            'log_info'=>'功能对应api',
            'remark'=>serialize($params)
        ]);
        return $this->formatOutput($res);
    }

    public function funcApiList(Request $request){
        $func_id = $request->input('func_id',0);
        $res = PermissionServices::funcApiList($func_id);
        return $this->formatOutput($res);
    }


    public function routesList(Request $request)
    {
        $params              = $request->all();
        //$params['type']      = data_get($params, 'type', 1);//1 func 2api
        $params['page']      = data_get($params, 'page', 1);
        $params['page_size'] = data_get($params, 'page_size', 20);
        $datas               = PermissionServices::routesList($params);
        return $this->formatOutput($datas);
    }

    public function routesAdd(PermissionRequest $request)
    {
        $params = $request->all();
        $data   = PermissionServices::routesAdd($params);
        $res    = $data ? ['成功'] : ['失败'];
        addAdminLogs([
            'table_name'=>'routes',
            'log_info'=>'api新增',
            'remark'=>serialize($params)
        ]);
        return $this->formatOutput($res);
    }

    public function routesUpdate(PermissionRequest $request){
        $params = $request->all();
        $data   = PermissionServices::routesUpdate($params);
        $res    = $data ? ['成功'] : ['失败'];
        addAdminLogs([
            'table_name'=>'routes',
            'tid'=>data_get($params,'id',0),
            'log_info'=>'api修改',
            'remark'=>serialize($params)
        ]);
        return $this->formatOutput($res);
    }

    public function routeDelete(Request $request){
        $params = $request->all();
        $id = data_get($params,'id',0);
        try{
            DB::beginTransaction();
            PermissionServices::routeDelete($id);
            DB::commit();
            addAdminLogs([
                'table_name'=>'routes',
                'tid'=>$id,
                'log_info'=>'api删除',
                'remark'=>serialize($params)
            ]);
            return $this->formatOutput('成功');
        }catch (\Exception $e){
            DB::rollBack();
            throw new \LogicException($e->getMessage());
        }
    }

    /**
     * 获取当前登录的shopId
     * @param Request $request
     * @return array
     */
    public function getShopId(Request $request)
    {
        $user   = authUser();
        $userExtra = App\Api\Auth\Models\Users::where('user_id', '=', $user->id)
            ->first();
        $shopId = data_get($userExtra, 'shop_id', '');
        $shop = User::find($shopId);
        $name = data_get($shop, 'name', '');
        if (empty($shopId)) {
            throw new \LogicException('未找到该用户对应的店铺信息', 400);
        }

        return $this->formatOutput([
            'shop_id' => $shopId,
            'shop_name' => $name,
        ]);
    }

    function permissionAdd(PermissionRequest $request)
    {
        $params = $request->all();
        $user = authUser();
        $permission = Permissions::where('shop_id', '=', $user->id)
            ->where('level', '=', 1)
            ->first();

        if (empty($permission)) {
            throw new \LogicException('非法操作', 110);
        }
        $data   = PermissionServices::permissionAdd($params);
        $res    = $data ? ['成功'] : ['失败'];
        return $this->formatOutput($res);
    }
}